<?php
class Admin_ProductController extends Zend_Controller_Action {
	private $_model;
	public function init() {
		$this->_model = new Application_Model_DbTable_Product ();
	}
	public function indexAction() {
		$filters = array ();
		
		// từ khóa
		$keyword = $this->_request->getParam ( 'keyword', '' );
		$filters ['keyword'] = $keyword;
		$this->view->keyword = $keyword;
		
		// phân loại
		$category = $this->_request->getParam ( 'category', 0 );
		$filters ['category'] = $category;
		$this->view->category = $category;
		
		// hang san xuat
		
		$manufacture = $this->_request->getParam ( 'manufacture', 0 );
		$filters ['manufacture'] = $manufacture;
		$this->view->manufacture = $manufacture;
		
		// từ giá
		$startPrice = $this->_request->getParam ( 'startPrice', null );
		$filters ['startPrice'] = $startPrice;
		$this->view->startPrice = $startPrice;
		
		// đến giá
		$endPrice = $this->_request->getParam ( 'endPrice', null );
		$filters ['endPrice'] = $endPrice;
		$this->view->endPrice = $endPrice;
		
		// từ ngày
		$fromDate = $this->_request->getParam ( 'fromDate', null );
		$filters ['fromDate'] = Cms_String_String::getDateFromString ( $fromDate );
		$this->view->fromDate = $fromDate;
		
		// đến ngày
		$toDate = $this->_request->getParam ( 'toDate', null );
		$filters ['toDate'] = Cms_String_String::getDateFromString ( $toDate, 'last' ); // chuyển về định dạng của mysql
		$this->view->toDate = $toDate;
		
		// trạng thái | status
		$status = $this->_request->getParam ( 'searchStatus', "" );
		$filters ['status'] = $status;
		$this->view->status = $status;
		
		// sắp xếp | order
		$order = $this->_request->getParam ( 'order', "" );
		if ($order != "") {
			list ( $orderBy, $orderType ) = explode ( '-', $order );
		} else {
			$orderBy = null;
			$orderType = null;
		}
		
		// get item count per page
		$icpp = $this->_request->getParam ( 'icpp', 20 );
		
		// get current page number
		$currentPage = $this->_request->getParam ( 'page', 1 );
		
		$list = $this->_model->getList ( $filters, $orderType, $orderBy );
		
		// pagination
		$paginator = Zend_Paginator::factory ( $list );
		$paginator->setCurrentPageNumber ( $currentPage );
		$paginator->setItemCountPerPage ( $icpp );
		$paginator->setPageRange ( 5 );
		
		// assign to view
		$this->view->paginator = $paginator;
		
		if ($this->_request->getParam ( 'ajax' ) == 'enable') {
			$this->_helper->layout ()->disableLayout ( true );
		}
	}
	public function insertAction() {
		$form = new Admin_Form_InsertProduct ();
		$form->removeElement ( 'product_image' );
		$form->getDisplayGroup ( 'basic-info' )->removeElement ( 'product_image' );
		$form->getElement('file')->setDescription('');
		if ($this->_request->isPost ()) {
			$data = $this->_request->getPost ();
			
			// xử lý dữ liệu trước khi nhập vào
			$data ['product_price'] = str_replace ( ',', '', $data ['product_price'] );
			$data ['product_price_old'] = str_replace ( ',', '', $data ['product_price_old'] );
			
			if ($form->isValid ( $data )) {
				
				// xử lý ngày tháng
				if ($data ['product_saleoff_status'] == 1) {
					$pattern = '/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/';
					$subject_begin = $data ['product_saleoff_begin'];
					$subject_end = $data ['product_saleoff_end'];
					
					if (! preg_match ( $pattern, $subject_begin )) {
						$form->getElement ( 'product_saleoff_begin' )->addError ( 'Định dạng ko đúng' );
						$form->markAsError ();
					} elseif (! preg_match ( $pattern, $subject_end )) {
						$form->getElement ( 'product_saleoff_end' )->addError ( 'Định dạng ko đúng' );
						$form->markAsError ();
					} else {
						list ( $bDay, $bMonth, $bYear ) = explode ( '/', $data ['product_saleoff_begin'] );
						list ( $eDay, $eMonth, $eYear ) = explode ( '/', $data ['product_saleoff_end'] );
						$saleoffBegin = mktime ( 0, 0, 0, ( int ) $bMonth, ( int ) $bDay, ( int ) $bYear );
						$saleoffEnd = mktime ( 23, 59, 59, ( int ) $eMonth, ( int ) $eDay, ( int ) $eYear );
						
						// kiem tra thoi gian hop le hay ko?
						if ($saleoffBegin >= $saleoffEnd) {
							$form->getElement ( 'product_saleoff_begin' )->addError ( "Thời gian bắt đầu '" . date ( 'd/m/Y', $saleoffBegin ) . "' không được trễ hơn thời gian kết thúc" );
							$form->getElement ( 'product_saleoff_end' )->addError ( "Thời gian kết thúc '" . date ( 'd/m/Y', $saleoffEnd ) . "' không được trễ hơn thời gian kết thúc" );
							$form->markAsError ();
						} elseif ($saleoffEnd <= time ()) { // kiem tra thoi gian ket thuc
							$form->getElement ( 'product_saleoff_end' )->addError ( 'Thời gian kết thúc không hợp lệ' );
							$form->markAsError ();
						} else {
							$data ['product_saleoff_begin'] = $saleoffBegin;
							$data ['product_saleoff_end'] = $saleoffEnd;
						}
					} // end else
				} // end if product_saleoff_status
				
				$row = $this->_model->createRow ( $data );
				$row->product_alias = Cms_String_String::toAlias ( $row->product_name );
				$row->product_creation_time = date ( 'Y-m-d H:i:s' );
				$row->product_last_modified_time = date ( 'Y-m-d H:i:s' );
				$row->creation_time = time();
				$row->last_modified_time = time();
				
				// xử lý hình ảnh
				if ($form->file->receive () && $form->getValue ( 'file' ) != "") {
					$dir = PUBLIC_PATH . '/uploads/images/products';
					$cms_image = new Cms_Image_PhpThumb ( $dir . '/tmp/' . $form->getValue ( 'file' ), $row->product_alias );
					$filename = $cms_image->toResize ( array (
							1 => array (
									'width' => '120',
									'height' => '120',
									'dir' => $dir . '/thumbs' 
							),
							2 => array (
									'width' => '400',									
									'height' => '400',
									'dir' => $dir . '/400x400' 
							) 
					) );
					$row->product_image = $filename;
					
					// xóa hình ảnh gốc
					@unlink ( $dir . '/tmp/' . $filename );
				}
				
				// kiểm tra lỗi nếu không thì lưa vào database
				if (! $form->hasErrors ()) {
					$row->save ();
					$this->_helper->flashMessenger ( 'Thêm sản phẩm thành công!' );
					$this->_helper->redirector ( 'index', 'product', 'admin' );
				} else {
					$this->_helper->flashMessenger ( 'Thêm thất bại!' );
				}
			}
		}
		$this->view->form = $form;
	}
	public function updateAction() {
		//add js, css
		$this->view->headScript()->appendFile(PUBLIC_RESOURCE.'/skins/admin/js/fancyBox/source/jquery.fancybox.js');
		$this->view->headScript()->appendFile(PUBLIC_RESOURCE.'/skins/admin/js/fancyBox/lib/jquery.mousewheel-3.0.6.pack.js');
		$this->view->headLink()->appendStylesheet(PUBLIC_RESOURCE.'/skins/admin/js/fancyBox/source/jquery.fancybox.css');
		
		// get id from request
		$id = $this->_request->getParam ( 'id' );
		
		// lấy đối tượng dựa vào id
		// $select = $this->_model->select()->where('product_id = ?',$id);
		// $row = $this->_model->fetchRow($select);
		$row = $this->_model->find ( $id )->current ();
		
		if (! $row) {
			$this->_helper->flashMessenger ( 'Mã sản phẩm không tồn tại!' );
		} else {
			$form = new Admin_Form_InsertProduct ();
			$form->getElement('file')->setDescription('<a href="'.$this->view->baseUrl('/admin/product/upload/id/'.$id.'/?lo=false').'" class="fancybox fancybox.ajax more-image"/>Nhập thêm hình ảnh</a>');
			if ($this->_request->isPost ()) {
				
				// Phần dữ liệu cần xử lý trước khi nhập vào
				$data = $this->_request->getPost ();
				
				// xử lý tiền tệ
				$data ['product_price'] = str_replace ( ',', '', $data ['product_price'] );
				$data ['product_price_old'] = str_replace ( ',', '', $data ['product_price_old'] );
				
				if ($form->isValid ( $data )) {
					
					// lấy tất cả giá trị trong form
					$params = array ();
					$params = $form->getValues ();
					
					if ($params ['product_saleoff_status'] == 1) {
						
						// xử lý ngày tháng
						$pattern = '/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/';
						$subject_begin = $params ['product_saleoff_begin'];
						$subject_end = $params ['product_saleoff_end'];
						
						if (! preg_match ( $pattern, $subject_begin )) {
							$form->getElement ( 'product_saleoff_begin' )->addError ( 'Định dạng ko đúng' );
							$form->markAsError ();
						} elseif (! preg_match ( $pattern, $subject_end )) {
							$form->getElement ( 'product_saleoff_end' )->addError ( 'Định dạng ko đúng' );
							$form->markAsError ();
						} else {
							list ( $bDay, $bMonth, $bYear ) = explode ( '/', $params ['product_saleoff_begin'] );
							list ( $eDay, $eMonth, $eYear ) = explode ( '/', $params ['product_saleoff_end'] );
							$saleoffBegin = mktime ( 0, 0, 0, ( int ) $bMonth, ( int ) $bDay, ( int ) $bYear );
							$saleoffEnd = mktime ( 23, 59, 59, ( int ) $eMonth, ( int ) $eDay, ( int ) $eYear );
							
							// kiem tra thoi gian hop le hay ko?
							if ($saleoffBegin >= $saleoffEnd) {
								$form->getElement ( 'product_saleoff_begin' )->addError ( "Thời gian bắt đầu '" . date ( 'd/m/Y', $saleoffBegin ) . "' không được trễ hơn thời gian kết thúc" );
								$form->getElement ( 'product_saleoff_end' )->addError ( "Thời gian kết thúc '" . date ( 'd/m/Y', $saleoffEnd ) . "' không được trễ hơn thời gian kết thúc" );
								$form->markAsError ();
							} elseif ($saleoffEnd <= time ()) { // kiem tra thoi gian ket thuc
								$form->getElement ( 'product_saleoff_end' )->addError ( 'Thời gian kết thúc không hợp lệ' );
								$form->markAsError ();
							} else {
								$params ['product_saleoff_begin'] = $saleoffBegin;
								$params ['product_saleoff_end'] = $saleoffEnd;
							}
						}
					} // end if product_saleoff_status
					  
					// hủy bổ giá trị file và image ( giá trị image sẽ = rỗng khi post())
					unset ( $params ['file'] );
					unset ( $params ['product_image'] );
					
					$params ['product_alias'] = Cms_String_String::toAlias ( $form->getValue ( 'product_name' ) );
					$params ['product_last_modified_time'] = date ( 'Y-m-d H:i:s' );
					$params ['last_modified_time'] = time ();
					
					// nếu có thay đổi hình ảnh
					if ($form->file->receive () && $form->getValue ( 'file' ) != '') {
						
						$dir = PUBLIC_PATH . '/uploads/images/products';
						
						// xóa những hình ảnh củ
						@unlink ( $dir . '/thumbs/' . $row->product_image );
						@unlink ( $dir . '/400x400/' . $row->product_image );
						
						// crop and get new file's name
						$cms_image = new Cms_Image_PhpThumb ( $dir . '/tmp/' . $form->getValue ( 'file' ), $params ['product_alias'] );
						$filename = $cms_image->toResize ( array (
								1 => array (
										'width' => '120',
										'height' => '120',
										'dir' => $dir . '/thumbs' 
								),
								2 => array (
										'width' => '400',
										'height' => '400',
										'dir' => $dir . '/400x400' 
								) 
						) );
						
						// remove origin image
						@unlink ( $dir . '/tmp/' . $filename );
						
						// save new file's name to arr
						$params ['product_image'] = $filename;
					}
					
					if (! $form->hasErrors ()) {
						// $this->_model->update($params,"product_id = {$id}");
						$row->setFromArray ( $params );
						$row->save ();
						$this->_helper->flashMessenger ( 'Cập nhật sản phẩm thành công!' );
						$this->_helper->redirector('index','product','admin');
					} else {
						$this->_helper->flashMessenger ( 'Cập nhật thất bại!' );
						//$row->setFromArray ( $params );
					}
				}
			}
			// $row = $this->_model->fetchRow($select);
			
			// format date time
			$row->product_saleoff_begin = date ( 'd/m/Y', $row->product_saleoff_begin );
			$row->product_saleoff_end = date ( 'd/m/Y', $row->product_saleoff_end );
			
			$form->populate ( $row->toArray () );
			$form->product_image->setAttrib ( 'src', PUBLIC_RESOURCE . '/uploads/images/products/thumbs/' . $row->product_image );
			$this->view->form = $form;
		}
	}
	public function deleteAction() {
		$status = 0;
		$id = @( array ) $this->_request->getParam ( 'id' );
		$rows = $this->_model->fetchAll ( $this->_model->select ()->where ( 'product_id IN (?)', $id ) );
		$productImageMD = new Application_Model_DbTable_ProductImage ();
		if (count ( $rows ) > 0) {
			foreach ( $rows as $row ) {
				$dir = PUBLIC_PATH . '/uploads/images/products';
				
				// xóa hình ảnh ở bản phụ
				$imageRows = $productImageMD->fetchAll ( $productImageMD->select ()->where ( 'product_image_product_id = ?', $row->product_id ) );
				if (count ( $imageRows )) {
					foreach ( $imageRows as $imageRow ) {
						@unlink ( $dir . '/thumbs/' . $imageRow->product_image_name );
						@unlink ( $dir . '/400x400/' . $imageRow->product_image_name );
						@unlink ( $dir . '/tmp/' . $imageRow->product_image_name );
						$imageRow->delete ();
					}
				}
				// xóa hình ở bản chính
				@unlink ( $dir . '/thumbs/' . $row->product_image );
				@unlink ( $dir . '/400x400/' . $row->product_image );
				$row->delete ();
				$status = 1;
			}
			$this->_helper->flashMessenger ( 'Xóa dữ liệu thành công!' );
			$this->_helper->redirector ( 'index', 'product', 'admin' );
		}
	}
	public function changestatusAction() {
		$status = "";
		$id = $this->_request->getParam ( 'id' );
		
		$row = $this->_model->fetchRow ( $this->_model->select ()->where ( 'product_id = ?', $id ) );
		
		if (! $row) {
			$status ['error'] = "sản phẩm không tồn tại";
		} else {
			$row->product_status = ( int ) (1 - $row->product_status);
			$status ['status'] = $row->product_status;
			try {
				$row->save ();
			} catch ( Exception $e ) {
				$status ['errors'] = "lỗi {$e->getMessage()}";
			}
		}
		$this->_helper->viewRenderer->setNoRender ( true );
		$this->_helper->layout ()->disableLayout ();
		$this->_helper->json->sendJson ( $status );
	}
	public function changehotAction() {
		$status = "";
		$id = $this->_request->getParam ( 'id' );
		
		$row = $this->_model->find ( $id )->current ();
		
		if (! $row) {
			$status ['error'] = "sản phẩm không tồn tại";
		} else {
			$row->product_hot = ( int ) (1 - $row->product_hot);
			$status ['status'] = $row->product_hot;
			try {
				$row->save ();
			} catch ( Exception $e ) {
				$status ['errors'] = "lỗi {$e->getMessage()}";
			}
		}
		$this->_helper->viewRenderer->setNoRender ( true );
		$this->_helper->layout ()->disableLayout ();
		$this->_helper->json->sendJson ( $status );
	}
	public function uploadAction() {
		$id = $this->_request->getParam ( 'id' );
		$this->view->id = $id;
		
		//Add js,css
		$this->view->headScript()->appendFile(PUBLIC_RESOURCE.'/skins/admin/js/fancyBox/source/jquery.fancybox.js');
		$this->view->headScript()->appendFile(PUBLIC_RESOURCE.'/skins/admin/js/fancyBox/lib/jquery.mousewheel-3.0.6.pack.js');
		$this->view->headLink()->appendStylesheet(PUBLIC_RESOURCE.'/skins/admin/js/fancyBox/source/jquery.fancybox.css');
		
		$this->view->headScript()->appendFile(PUBLIC_RESOURCE.'/skins/admin/js/fancyBox/helpers/jquery.fancybox-buttons.js');
		$this->view->headLink()->appendStylesheet(PUBLIC_RESOURCE.'/skins/admin/js/fancyBox/helpers/jquery.fancybox-buttons.css');
		
		if($this->_request->getParam('lo')=="false"){
			$this->_helper->layout()->disableLayout();
			$this->view->headLink()->appendStylesheet(PUBLIC_RESOURCE.'/skins/admin/css/style.css');
		}

	
	}
	
	public function getlistimageAction(){
		$id = $this->_request->getParam ( 'id' );
		$productImageMD = new Application_Model_DbTable_ProductImage ();
		$images = $productImageMD->fetchAll ( $productImageMD->select ()->where ( 'product_image_product_id = ?', $id ) );
		$this->view->images = $images;
		$this->_helper->layout()->disableLayout();
	}
	public function uploadtmpAction() {
		// tat layout
		$this->_helper->layout ()->disableLayout ( true );
		$options = array (
				'script_url' => PUBLIC_RESOURCE,
				'upload_dir' => PUBLIC_PATH . '/uploads/images/products/tmp/',
				'upload_url' => PUBLIC_RESOURCE . '/uploads/images/products/tmp/',
				'image_versions' => array (
						'' => array (
								'auto_orient' => true 
						),
						
						'medium' => array (
								'max_width' => 400,
								'max_height' => 400,
								'upload_dir' => PUBLIC_PATH . '/uploads/images/products/400x400/',
								'upload_url' => PUBLIC_RESOURCE . '/uploads/images/products/400x400/' 
						),
						
						'thumbnail' => array (
								'upload_dir' => PUBLIC_PATH . '/uploads/images/products/thumbs/',
								'upload_url' => PUBLIC_RESOURCE . '/uploads/images/products/thumbs/',
								'max_width' => 120,
								'max_height' => 120 
						) 
				) 
		);
		$uploadHandler = new Cms_Image_UploadHandlerCustom ( $options );
		
		$file = $uploadHandler->getFileName ();
		
		$id = $this->_request->getParam ( 'id' );
		$productImageMD = new Application_Model_DbTable_ProductImage ();
		$productImageRow = $productImageMD->createRow ();
		$productImageRow->product_image_product_id = $id;
		$productImageRow->product_image_name = $file->name;
		$productImageRow->save ();
	}
	public function deleteimageAction() {
		$this->_helper->layout ()->disableLayout ( true );
		$id = $this->_request->getParam ( 'id' );
		$productImageMD = new Application_Model_DbTable_ProductImage ();
		$dir = PUBLIC_PATH . '/uploads/images/products';
		$row = $productImageMD->find ( $id )->current ();
		@unlink ( $dir . '/thumbs/' . $row->product_image_name );
		@unlink ( $dir . '/400x400/' . $row->product_image_name );
		@unlink ( $dir . '/tmp/' . $row->product_image_name );
		$row->delete ();
	}
}

